﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using ZK.Qymd_TransManage.ServiceReferenceApi;
using ZK.Qymd_TransManage.Model;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace ZK.Qymd_TransManage
{
    public partial class SalesSummary : Form
    {
        public SalesSummary()
        {
            InitializeComponent();

        }

        private void btnSearchInfo_Click(object sender, EventArgs e)
        {
            AccessApiServiceClient client = new AccessApiServiceClient();
            List<DataGridModel> ListDataModel = new List<DataGridModel>();
            TruckSummaryInfoDto model = new TruckSummaryInfoDto();
            model.煤种 = txtCoalType.Text;
            model.收货单位 = txtReceivingPartyName.Text;
            model.起始时间 = dtStart.Text;
            model.结束时间 = dtEnd.Text;
            ApiLoadingResponseDto bill = client.GetSummaryInfo(model);
            DataTable dt = bill.dt;
            if (dt.Rows.Count != 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    DataGridModel dataModel = new DataGridModel();
                    dataModel.ReceivingPartyName = dr["收货单位"].ToString();
                    dataModel.CoalType = dr["货物名称"].ToString();
                    dataModel.CarNum = dr["车数"].ToString();
                    double AddNetWeight = Convert.ToDouble(dr["煤总量"].ToString());
                    dataModel.AddNetWeight = String.Format("{0:F}", AddNetWeight);
                    ListDataModel.Add(dataModel);
                }
                dgView.AutoGenerateColumns = false;
                dgView.DataSource = ListDataModel;
                client.Close();
            }
        }
        private void ExportExcels(string fileName, DataGridView myDGV)
        {
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，可能您的电脑未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
                                                                                                                                  //写入标题
            for (int i = 0; i < myDGV.ColumnCount; i++)
            {
                worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
            }
            //写入数值
            for (int r = 0; r < myDGV.Rows.Count; r++)
            {
                for (int i = 0; i < myDGV.ColumnCount; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();//强行销毁
            MessageBox.Show("文件： " + fileName + "保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            //string a = "D:" + "\\KKHMD.xlsx";
            ExportExcelsByNPOI("汇总", dgView);


            //FolderBrowserDialog dialog = new FolderBrowserDialog();//弹出选择文件路径
            //dialog.Description = "请选择文件路径";

            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    string foldPath = dialog.SelectedPath;
            //    //DirectoryInfo theFolder = new DirectoryInfo(foldPath);

            //    ////theFolder 包含文件路径

            //    //FileInfo[] dirInfo = theFolder.GetFiles();
            //    ////遍历文件夹                
            //    //foreach (FileInfo file in dirInfo)
            //    //{
            //    //    MessageBox.Show(file.ToString());
            //    //}
            //    string path = foldPath + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";//拼接路径
            //    #region 表头
            //    string cTitle = "车辆过磅信息";
            //    List<string> cName = new List<string>();
            //    cName.Add("车牌号");
            //    cName.Add("毛重");
            //    cName.Add("皮重");
            //    cName.Add("净重");
            //    cName.Add("货物名称");
            //    cName.Add("发货单位");
            //    cName.Add("收货单位");
            //    cName.Add("运输单位");
            //    cName.Add("毛重时间");
            //    cName.Add("皮重时间");
            //    cName.Add("作废标志");
            //    cName.Add("毛重计量员");
            //    cName.Add("称重日期");
            //    #endregion
            //    // ListDataModel.Add(new DataGridModel() { TruckNum = "asdqwe" });//数据源
            //    if (Com.DataToExcel.dt2csv(Com.DataToExcel.ToDataTable(ListDataModel), path, cTitle, string.Join(",", cName)))
            //    {
            //        MessageBox.Show("导出成功");
            //    }
            //    else
            //    {
            //        MessageBox.Show("导出失败");
            //    }
            //}




        }

        private void ExportExcelsByNPOI(string fileName, KryptonDataGridView dgv)
        {
            if (dgv.Rows.Count == 0)
            {
                return;
            }
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel 2003格式|*.xls";
            sfd.FileName = fileName + DateTime.Now.ToString("yyyyMMddHHmmssms");
            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = (HSSFSheet)wb.CreateSheet(fileName);
            HSSFRow headRow = (HSSFRow)sheet.CreateRow(0);
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                HSSFCell headCell = (HSSFCell)headRow.CreateCell(i, CellType.String);
                headCell.SetCellValue(dgv.Columns[i].HeaderText);
            }
            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                HSSFRow row = (HSSFRow)sheet.CreateRow(i + 1);
                for (int j = 0; j < dgv.Columns.Count; j++)
                {
                    HSSFCell cell = (HSSFCell)row.CreateCell(j);
                    if (dgv.Rows[i].Cells[j].Value == null)
                    {
                        cell.SetCellType(CellType.Blank);
                    }
                    else
                    {
                        if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Int32"))
                        {
                            cell.SetCellValue(Convert.ToInt32(dgv.Rows[i].Cells[j].Value));
                        }
                        else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.String"))
                        {
                            cell.SetCellValue(dgv.Rows[i].Cells[j].Value.ToString());
                        }
                        else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Single"))
                        {
                            cell.SetCellValue(Convert.ToSingle(dgv.Rows[i].Cells[j].Value));
                        }
                        else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Double"))
                        {
                            cell.SetCellValue(Convert.ToDouble(dgv.Rows[i].Cells[j].Value));
                        }
                        else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.Decimal"))
                        {
                            cell.SetCellValue(Convert.ToDouble(dgv.Rows[i].Cells[j].Value));
                        }
                        else if (dgv.Rows[i].Cells[j].ValueType.FullName.Contains("System.DateTime"))
                        {
                            cell.SetCellValue(Convert.ToDateTime(dgv.Rows[i].Cells[j].Value).ToString("yyyy-MM-dd"));
                        }
                    }

                }

            }
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                sheet.AutoSizeColumn(i);
            }
            using (FileStream fs = new FileStream(sfd.FileName, FileMode.Create))
            {
                wb.Write(fs);
            }
            MessageBox.Show("导出成功！", "导出提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}